#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socketserver
import pickle
from Rule import Poker,Card,Operation
from collections import deque
players = deque()
users = "001 002 101 102".split()
cards__ = Poker()
class MyTCPHandler(socketserver.BaseRequestHandler):
    #    def __init__(self,request, client_address, server):
    #        super().__init__(request, client_address, server)
    name = None
    def handle(self):
        """
        所有请求的交互都是在handle里执行的,
        接收到的对象以代码表示请求，例如1001：请求发牌
        发送的对象一定要以struct结构来封装，方便管理
        """
        while True:
            try:
                # print(self.client_address)
                data = self.request.recv(1024)
                if data:
                    code,*msg = pickle.loads(data)
                    if code == Operation.login:
                        print(msg)
                        id_,name,*ots = msg
                        if id_ in users: #这一步是验证，以后改为从数据库验证，现在先用列表验证。
                            if name not in players:
                                self.name = name
                                players.append(name)
                            print("登录成功",players)
                            # 登陆成功了就给玩家发牌
                            cards = (cards__.pop() for i in range(3))
                            userInfo = {
                                            "user0":[self.name,cards],
                                            "user1":[]
                                        }
                            self.request.send(pickle.dumps((200,"登录成功",cards__.pop(),cards__.pop(),cards__.pop())))
                        else:
                            print("非法登录")
                            self.request.send(pickle.dumps((404,"非法登录")))
                            self.request.close()
                            break
                    elif code == Operation.add_1:
                        pass
                    elif code == Operation.add_2:
                        pass
                    elif code == Operation.add_3:
                        pass
                    elif code == Operation.pass_:
                        pass
                    elif code == Operation.fllow_:
                        pass
                    elif code == Operation.pass_:
                        pass
                    elif code == Operation.quit_:
                        pass
                    elif code == Operation.close_:
                        pass
                else:
                    if self.name:
                        players.remove(self.name)
                    break


            except ConnectionResetError as e:
                print("err ", e)
                break


if __name__ == "__main__":
    print("开始启动服务")
    HOST, PORT = "127.0.0.1", 54321
    # HOST, PORT = "0.0.0.0", 9999 #Linux
    server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()
